package com.pig4cloud.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.mall.product.entity.*;
import com.pig4cloud.mall.product.enums.AttrEnum;
import com.pig4cloud.mall.product.mapper.SpuInfoMapper;
import com.pig4cloud.mall.product.service.*;
import com.pig4cloud.mall.product.vo.*;
import com.pig4cloud.pig.common.core.util.PageResult;
import com.pig4cloud.pig.common.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * spu信息
 *
 * @author fangyu
 * @date 2020-11-25 14:58:46
 */
@Slf4j
@Service
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoMapper, SpuInfo> implements SpuInfoService {

	@Resource
	private SpuInfoMapper spuInfoMapper;
	@Resource
	private SkuInfoService skuInfoService;
	@Resource
	private SpuImagesService spuImagesService;
	@Resource
	private SpuInfoDescService spuInfoDescService;
	@Resource
	private AttrService attrService;
	@Resource
	private ProductAttrValueService productAttrValueService;
	@Resource
	private SkuImagesService skuImagesService;
	@Resource
	private SkuSaleAttrValueService skuSaleAttrValueService;

	@Override
	public R queryByCondition(Map<String, Object> params) {
		long current = 1;
		long size = 10;
		if (StringUtils.isNotEmpty((String) params.get("current"))) {
			log.debug("current => {}", params.get("current"));
			current = Long.parseLong((String) params.get("current"));
		}
		if (StringUtils.isNotEmpty((String) params.get("size"))) {
			log.debug("size => {}", params.get("size"));
			size = Long.parseLong((String) params.get("size"));
		}
		Page<SpuInfo> p = new Page<>(current, size);
		IPage<SpuInfo> page = spuInfoMapper.querySpuInfo(p, params);

		List<SpuInfoVo> spuInfoVoList = new ArrayList<>();
		page.getRecords().forEach(item -> {
			SpuInfoVo spuInfoVo = new SpuInfoVo();
			BeanUtils.copyProperties(item, spuInfoVo);
			List<SpuImages> spuImages = spuImagesService.list(new QueryWrapper<SpuImages>().eq("spu_id", item.getId()));
			spuInfoVo.setImageList(spuImages);
			spuInfoVoList.add(spuInfoVo);
		});

		return R.ok(PageResult.buildPage(page, spuInfoVoList));
	}

	@Override
	public R queryDetailBySpuId(Long spuId) {
		SpuInfoDesc spuInfoDesc = spuInfoDescService.getById(spuId);
		if (spuInfoDesc == null) {
			return R.failed();
		}
		List<String> imgList = new ArrayList<>();
		if (spuInfoDesc.getDecript().contains(",")) {
			imgList = Arrays.asList(spuInfoDesc.getDecript().split(","));
		} else {
			imgList.add(spuInfoDesc.getDecript());
		}
		return R.ok(imgList);
	}

	@Override
	@Transactional
	public R addSpu(SpuAddVo spuAddVo) {

		SpuInfo spuInfo = new SpuInfo();
		BeanUtils.copyProperties(spuAddVo, spuInfo);
		spuInfo.setCatalogId(spuAddVo.getCategoryId());
		// 一、保存基础spu信息
		this.save(spuInfo);

		// 二、保存spu描述图片
		SpuInfoDesc spuInfoDesc = new SpuInfoDesc();
		spuInfoDesc.setSpuId(spuInfo.getId());
		List<String> description = spuAddVo.getDescription();
		spuInfoDesc.setDecript(String.join(",", description));
		spuInfoDescService.save(spuInfoDesc);

		// 三、保存spu图片集
		List<String> images = spuAddVo.getImages();
		if (images != null && images.size() > 0) {
			List<SpuImages> spuImagesList = images.stream().map(img -> {
				SpuImages spuImages = new SpuImages();
				spuImages.setSpuId(spuInfo.getId());
				spuImages.setImgUrl(img);
				return spuImages;
			}).collect(Collectors.toList());
			spuImagesService.saveBatch(spuImagesList);
		}

		// 四、保存spu的规格参数
		List<BaseAttr> baseAttrs = spuAddVo.getBaseAttrs();
		if (baseAttrs != null && baseAttrs.size() > 0) {
			List<ProductAttrValue> productAttrValueList = baseAttrs.stream().map(baseAttr -> {
				ProductAttrValue productAttrValue = new ProductAttrValue();
				productAttrValue.setAttrId(baseAttr.getAttrId());
				productAttrValue.setAttrValue(baseAttr.getAttrValues());
				productAttrValue.setQuickShow(baseAttr.getIsShow());
				Attr attr = attrService.getById(baseAttr.getAttrId());
				productAttrValue.setAttrName(attr.getAttrName());
				productAttrValue.setSpuId(spuInfo.getId());
				return productAttrValue;
			}).collect(Collectors.toList());
			productAttrValueService.saveBatch(productAttrValueList);
		}


		// TODO 五、保存spu的积分信息 gulimall_sms sms_spu_bounds 待添加
		// todo 远程调用

		// 六、保存spu的所有sku信息
		List<Sku> skus = spuAddVo.getSkus();
		if (skus != null && skus.size() > 0) {
			// 获取默认图片路径
			skus.forEach(sku -> {
				String defaultImage = "";
				for (Images image : sku.getImages()) {
					if (image.getDefaultImg() == AttrEnum.DEFAULT_IMG.getCode()) {
						defaultImage = image.getImgUrl();
					}
				}
				SkuInfo skuInfo = new SkuInfo();
				BeanUtils.copyProperties(sku, skuInfo);
				skuInfo.setSpuId(spuInfo.getId());
				skuInfo.setBrandId(spuInfo.getBrandId());
				skuInfo.setCatalogId(spuInfo.getCatalogId());
				skuInfo.setSaleCount(0L);
				skuInfo.setSkuDefaultImg(defaultImage);
				// 1.sku基本信息 pms_sku_info
				skuInfoService.save(skuInfo);

				// skuId
				Long skuId = skuInfo.getSkuId();
				List<SkuImages> skuImagesList = sku.getImages().stream().map(img -> {
					SkuImages skuImages = new SkuImages();
					skuImages.setSkuId(skuId);
					skuImages.setDefaultImg(img.getDefaultImg());
					skuImages.setImgUrl(img.getImgUrl());
					return skuImages;
				}).filter(item -> {
					// 只保存有图片路径的
					String imgUrl = item.getImgUrl();
					return (!StringUtils.isEmpty(imgUrl));
				}).collect(Collectors.toList());
				// 2.sku图片信息 pms_sku_images
				skuImagesService.saveBatch(skuImagesList);

				List<AttrVo> attrs = sku.getAttr();
				List<SkuSaleAttrValue> skuSaleAttrValueList = attrs.stream().map(attrVo -> {
					SkuSaleAttrValue skuSaleAttrValue = new SkuSaleAttrValue();
					BeanUtils.copyProperties(attrVo, skuSaleAttrValue);
					skuSaleAttrValue.setSkuId(skuId);
					return skuSaleAttrValue;
				}).collect(Collectors.toList());
				// 3.sku属性信息 pms_sku_sale_attr_value
				skuSaleAttrValueService.saveBatch(skuSaleAttrValueList);

				// todo 4.sku优惠满减信息 gulimall_sms sms_sku_full_reduction / sms_sku_ladder / sms_member_price 待添加
				// todo 远程调用
			});
		}
		return R.ok("添加成功!");
	}
}
